package cn.hss.jdbc.utils;

import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**工具类
 * @author 作者：HeShaoShuai
 * @Email 邮箱：2569819541@qq.com
 * @Date 日期：2023/5/5 16:02
 * @Package 包名：cn.hss.jdbc.utils
 * @Project 项目名：JavaSE
 * @Version 1.0
 */
public class JDBCUtil {
	private static String url;
	private static String userName;
	private static String pwd;
	private static String driver;
	/*properties文件只读一次*/
	static {
		//读取资源文件，获取值
		try {
			//1.创建Properties
			Properties pro = new Properties();
			//2.加载资源文件
			ClassLoader loader = JDBCUtil.class.getClassLoader();
			//动态获取src路径下的文件的方式-类加载器
//            URL resource = loader.getResource("jdbc.properties");
//            String path = resource.getPath();
//            pro.load(new FileReader(path));
			InputStream is =
					loader.getResourceAsStream("jdbc.properties");
			pro.load(is);
			//3.获取属性值
			url = pro.getProperty("url");
			userName = pro.getProperty("user");
			pwd = pro.getProperty("password");
			driver = pro.getProperty("driver");
			//4.注册驱动
			Class.forName(driver);
		} catch (IOException e) {
			throw new RuntimeException("资源文件找不到");
		}catch (ClassNotFoundException e){
			throw new RuntimeException("驱动类找不到");
		}
	}
	/*获取连接方法*/
	public static Connection getConn(){
		Connection conn= null;
		try {
			conn = DriverManager.getConnection(
					url,userName,pwd);
		} catch (SQLException throwables) {
			throw new RuntimeException("连接失败");
		}
		return conn;
	}
	/*释放资源方法*/
	//使用反射实现不同流对象的关闭
	public static <T> void closeIO(T t){
		try {
			//利用反射，获取Class对象
			Class<?> aClass = t.getClass();
			Method close = aClass.getMethod("close");
			//执行方法
			close.invoke(t);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}